<?php
require_once 'config.php';
require_once 'User.php';

class App {
	private static $request = array();
	private static $pageMap = array();
	private static $page;

	public static function init() {
		session_start();
		spl_autoload_register(__CLASS__.'::__autoload');
                set_error_handler(__CLASS__."::errorHandler");
		global $PAGE_MAP;
		self::$request = $_REQUEST;
		self::$pageMap = $PAGE_MAP;

                User::tryReviveSession();
		
		self::loadPage(self::getRequest('page','Login'));
	}
	
	public static function getRequest($key, $default = null) {
		if (isset(self::$request[$key])) {
			return self::$request[$key];
		}
		return $default;
	}
	
	public static function loadPage($name) {
		//if (!isset(self::$pageMap[$name])) {
		//	$pageClass = 'NotFound';
		//} else {
		//	$pageClass = self::$pageMap[$name];
		//}
		$pageClass = $name;
		self::$page = new $pageClass();
                if (self::$page->checkPermissions()) {
                    self::$page->display();
                } else {
                    die("<h1>Unauthenticated</h1>");
                }
	}
	
	public static function __autoload($name) {
		if (file_exists("pages/$name.php")) {
			include_once "pages/$name.php";
		} elseif (file_exists("app/$name.php")) {
			include_once "app/$name.php";
		}
	}
	
	public static function redirect($pageName) {
		header("Location: index.php?page=$pageName");
		die();
	}

        public static function getActiveUser() {
            return isset($_SESSION['user']) ? $_SESSION['user'] : null;
        }

        public static function errorHandler($errno ,  $errstr ,  $errfile ,  $errline ,  $errcontext  ) {
            if ($errno == E_ERROR) {
                return false;
            }
            return true;
        }
	

}

?>